﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;

namespace MagicArena.framework.graphics._2d
{
    /// <summary>
    /// Singleton class for rendering sprites to screen. 
    /// Initialize MUST be called before it is used to render
    /// </summary>
    public class Render2dSingleton : IDrawable
    {
        #region Singleton non-threadsafe code
        private static Render2dSingleton _Instance;

        private Render2dSingleton(){ }

        public static Render2dSingleton Instance
        {
            get{
                if (_Instance == null)
                {
                    _Instance = new Render2dSingleton();
                }
                return _Instance;
            }
        }
        #endregion

        private SpriteBatch batcher;
        private GraphicsDevice GraphicsDevice;

        private List<RendererSprite> sprites = new List<RendererSprite>(10);

        #region Public Methods
        public void Initialize(Game g)
        {
            GraphicsDevice = g.GraphicsDevice;
            batcher = new SpriteBatch(GraphicsDevice);
        }

        

        public void Add(RendererSprite rs)
        {
            sprites.Add(rs);
        }
        public void Remove(RendererSprite rs)
        {
            sprites.Remove(rs);
        }
        public void Clear()
        {
            sprites.Clear();
        }
        #endregion

        #region IDrawable
        public void Draw(GameTime gameTime)
        {

            batcher.Begin();
            RendererSprite rs;
            for (int i = 0, len = sprites.Count; i < len; i++)
            {
                rs = sprites[i];
                if (rs.Enabled)
                {
                    batcher.Draw(rs.Texture, rs.Rect, Color.White);
                }
            }
            batcher.End();
        }

        public int DrawOrder
        {
            get { return 1; }
        }

        public event EventHandler<EventArgs> DrawOrderChanged;

        public bool Visible
        {
            get { return true; }
        }

        public event EventHandler<EventArgs> VisibleChanged;
        #endregion
    }
}
